package com.aabte.permissionframeworklearn.apacheshirodemo.shiro;

import com.aabte.permissionframeworklearn.apacheshirodemo.model.Permission;
import com.aabte.permissionframeworklearn.apacheshirodemo.model.Role;
import com.aabte.permissionframeworklearn.apacheshirodemo.model.User;
import com.aabte.permissionframeworklearn.apacheshirodemo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author Daniel
 */
@Slf4j
public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 授权时调用此方法
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("Start doGetAuthorizationInfo.");

        // 从Session中获取用户
        User user = (User) principalCollection.fromRealm(this.getClass().getName()).iterator().next();
        // 获取用户所有的权限列表
        List<String> havePermissions = new ArrayList<>();
        List<String> haveRoles = new ArrayList<>();
        Set<Role> roles = user.getRoles();
        if (CollectionUtils.isNotEmpty(roles)) {
            for (Role role : roles) {
                haveRoles.add(role.getRname());
                Set<Permission> permissions = role.getPermissions();
                if (CollectionUtils.isNotEmpty(permissions)) {
                    for (Permission permission : permissions) {
                        havePermissions.add(permission.getName());
                    }
                }
            }
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(havePermissions);
        authorizationInfo.addRoles(haveRoles);

        log.info("End doGetAuthorizationInfo. username: {}", user.getUsername());
        return authorizationInfo;
    }

    /**
     * 认证登录时调用此方法
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("Start doGetAuthenticationInfo.");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        User user = userService.findByUsername(username);
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());
        log.info("End doGetAuthenticationInfo.");
        return simpleAuthenticationInfo;
    }
}
